﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Identitymodels.Authorization
{
    public class ClaimsRequirementHandler : AuthorizationHandler<ClaimRequirement>
    {
        /// <summary>
        /// 授权方式（cookie, bearer, oauth, openid）
        /// </summary>
        private readonly IAuthenticationSchemeProvider _schemes;

        private readonly IHttpContextAccessor _accessor;
        private readonly JwtToken _jwt;
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="schemes"></param>
        public ClaimsRequirementHandler(IAuthenticationSchemeProvider schemes,IHttpContextAccessor accessor,JwtToken jwt)
        {
            _schemes = schemes;
            _accessor = accessor;
            _jwt = jwt;
        }
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       ClaimRequirement requirement)
        {
            //brear认证不能用的时候可以用这个
            try
            {
                var httpContext = _accessor.HttpContext;
                string authorizationHeader = httpContext.Request.Headers["Authorization"];
                var authorizationParts = authorizationHeader.Split(' ');
                if (authorizationParts.Length == 2 && authorizationParts[0] == "Bearer")
                {
                    var tokenValue = authorizationParts[1];
                    var value = JwtToken.SerializeJwt(tokenValue);
                    if (requirement.ClaimValue.Contains(value.Role))
                    {
                        context.Succeed(requirement);
                    }
                    else
                    {
                        context.Fail();
                    }

                }
            }
            catch(Exception e)
            {
                throw e;
            }



            //HttpContext httpContext = (context.Resource as AuthorizationFilterContext).HttpContext;
            //var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();
            //var result = httpContext.AuthenticateAsync(defaultAuthenticate.Name);


            //var claim = context.User.Claims.FirstOrDefault(c => c.Type == requirement.ClaimName);
            //if (claim != null && requirement.ClaimValue.Contains(claim.Value))
            //{
            //    context.Succeed(requirement);
            //}
            //else
            //{
            //    context.Fail();
            //}
        }
    }
}
